package binarysearch;

/**
 * @description:
 * @author: jhy
 * @time: 2021/4/22 17:02
 */
public class BinarySearchDemo2 {

    public static void main(String[] args) {
        int[] nums = {1, 2, 5, 7, 8, 9};
        int i = binarySearch(nums, 0,nums.length - 1,7);
        System.out.println(i);

    }

    /*
    参数说明：
    nums:在该数组中查找(有序)
    left:左指针  right:右指针
    target:要查找的目标值
     */
    public static int binarySearch(int[] nums,int left,int right,int target){

        while (left <= right){
            int mid = left + (right - left) / 2;
            if(nums[mid] == target){
                return mid;
            }else if(nums[mid] > target){ //target在mid的左边,向左递归
                return binarySearch(nums,left,mid-1,target);
            }else { //target在mid的右边，向右递归
                return binarySearch(nums,mid + 1,right,target);
            }
        }
        return -1;
    }
}
